package com.itmei.cicddemo.demos.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Author itmei
 * @Date 2023/12/20 20:34
 * @description: 服务层
 * @Title: ApiService
 * @Package com.itmei.cicddemo.demos.service
 */
@Service
public class ApiService {
    private static Map<String,Long> cityAreaIdMap = new HashMap<>();
    /**
     * 项目启动后会调用该方法
     * 获取所有城市AreaId
     *
     * @return
     */
    @PostConstruct
    public void getCity() {
        String cityJs = "https://j.i8tq.com/weather2020/search/city.js";
        //发送请求获取数据
        String cityStr = HttpUtil.createGet(cityJs).header("Referer", "http://www.weather.com.cn/").execute().body();
        //需要解析数据
        String cityJson = cityStr.replace("var city_data =", "");
        //创建集合存储数据
        //使用 NAMECN:AREAID
        JSONObject entries = JSONUtil.parseObj(cityJson);
        Set<String> keys = entries.keySet();
        for (String key : keys) {
            //System.out.println("第一层 省" + key);
            Set<String> citys = entries.getJSONObject(key).keySet();
            for (String city : citys) {
                //System.out.println("--第二层 城市" + city);
                Set<String> areas = entries.getJSONObject(key).getJSONObject(city).keySet();
                for (String area : areas) {
                    //System.out.println("---第三层 区:" + area);
                    JSONObject jsonObject = entries.getJSONObject(key).getJSONObject(city).getJSONObject(area);
                    //System.out.println(jsonObject.toString());
                    cityAreaIdMap.put(jsonObject.getStr("NAMECN"), jsonObject.getLong("AREAID"));
                }
            }
        }
    }

    private Long cityAreaIdMap(String city) {
        Long areaId = cityAreaIdMap.get(city);
        if (ObjectUtil.isEmpty(areaId)) {
            throw new RuntimeException("查询 "+city+" 城市异常,确认城市是否正确！");
        }
        return areaId;
    }

    /**
     * 获取实时城市天气
     *
     * @param city
     * @return
     */
    public JSONObject getRealWeather(String city) {
        //取出对应城市的areaid
        Long areaId = cityAreaIdMap(city);
        //实时天气的地址
        String REALWEATHER_URL = "http://d1.weather.com.cn/sk_2d/";
        //拼接请求地址
        String uri = REALWEATHER_URL + areaId + ".html";
        String res = HttpUtil.createGet(uri).timeout(10000).header("Referer", "http://www.weather.com.cn/").execute().body();
        //替换数据不然会影响json的解析
        String json = res.replace("var dataSK=", "");
        return JSONUtil.parseObj(json);
    }

}
